using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Reflection;
using System.Linq;

namespace XpoImport
{
    public class Importer
    {
        string connectionStringXAF = ConfigurationManager.ConnectionStrings["ConnectionStringXAF"].ConnectionString;
        string connectionStringSQL = ConfigurationManager.ConnectionStrings["ConnectionStringOLD"].ConnectionString;

        private DevExpress.Xpo.Session xpoSession = DevExpress.Xpo.Session.DefaultSession;
        private SqlConnection sqlConnection;

        public Importer(Assembly assembly)
        {
            DevExpress.Xpo.Session.DefaultSession.ConnectionString = connectionStringXAF;

            //DevExpress.Xpo.Session.DefaultSession.ClearDatabase();

            sqlConnection = new SqlConnection(connectionStringSQL);
            Imports = new List<ImportBase>();

            foreach (Type classType in assembly.GetTypes().Where(item => item.GetCustomAttributes(typeof(TableImportAttribute), false).Length > 0))
            {
                ImportBase importTask = new ImportBase(classType);
                Imports.Add(importTask);
            }

        }

        private List<ImportBase> _Imports;
        public List<ImportBase> Imports
        {
            get { return _Imports; }
            set
            {
                _Imports = value;
            }
        }

        public List<ImportBase> GetList()
        {
            return _Imports;
        }

        public void StartImport()
        {
            //ImportStarted(this, null);

            if (sqlConnection != null && sqlConnection.State != ConnectionState.Open)
                sqlConnection.Open();

            IOrderedEnumerable<ImportBase> importsOrderBy = Imports.OrderBy(importItem => importItem.ImportOrder);
            foreach (ImportBase item in importsOrderBy)
            {
                item.ImportProgress += new EventHandler(item_ImportProgress);
                item.ImportStarted += new EventHandler(item_ImportStarted);
                item.Execute(sqlConnection, xpoSession);
            }

            if (sqlConnection != null && sqlConnection.State != ConnectionState.Closed)
                sqlConnection.Close();

            ImportComplete(this, null);
            
            if (1==1)
                ImportError(this,null);
        }

        void item_ImportStarted(object sender, EventArgs e)
        {
            if (ImportStarted != null)
                ImportStarted(sender, e);
        }

        void item_ImportProgress(object sender, EventArgs e)
        {
            StepProgress(this, null);
        }

        public event EventHandler ImportError;
        public event EventHandler ImportStarted;
        public event EventHandler ImportComplete;

        public event EventHandler StepProgress;
    }
}
